<template>
  <div class="form-box">
    <h1 class="con-right-title">基本信息</h1>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="200px"
      class="demo-ruleForm"
      style="margin-bootom: 30px"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model.trim="ruleForm.name"
          :maxlength="30"
          show-word-limit
          clearable
          :disabled="isCheck"
          style="width:500px"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="image">
        <uploadSingImg
          :imgUrl="ruleForm.image"
          accept=".jpg,.jpeg,.png,.gif"
          :maxSize="5"
          @getImgUrl="getImgCover"
          :disabled="isCheck"
        >
          <template v-slot:imgInfo
            >（建议尺寸：750X1624 ，大小不超过5M，只可上传一张）</template
          >
        </uploadSingImg>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number
          v-model="ruleForm.stock"
          size="small"
          controls-position="right"
          :precision="0"
          :max="99999"
          :min="1"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="类别" prop="goodsType">
        <el-radio-group class="radioGroup" v-model="ruleForm.goodsType" @change="handleChange">
          <el-radio
            v-for="item in goodsTypeList"
            :key="item.dictValue"
            :label="item.dictValue"
            >{{ item.dictLabel }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <!-- v-if="ruleForm.goodsType === 'PHYSICAL'" 类别为实物时展示 -->
      <el-form-item
        label="商品价格"
        prop="priceShow"
        v-if="
          ruleForm.goodsType === 'PHYSICAL' || ruleForm.goodsType === 'COUPONS'
        "
      >
        <el-input-number
          v-model="ruleForm.priceShow"
          size="small"
          controls-position="right"
          :precision="2"
          :max="99999"
          :step="0.1"
          :min="0"
        ></el-input-number>
      </el-form-item>
      <!-- 类别为实物时展示 -->
      <el-form-item
        label="兑换所需鲜花"
        prop="price"
        :rules="{
          required: true,
          message: '您没有填写兑换所需鲜花数量',
          trigger: 'blur'
        }"
        v-if="ruleForm.goodsType === 'PHYSICAL'"
      >
        <el-input-number
          v-model="ruleForm.price"
          size="small"
          controls-position="right"
          :precision="0"
          :max="99999"
          :min="0"
        ></el-input-number>
        &nbsp;&nbsp;&nbsp;朵
      </el-form-item>
      <!-- 优惠券部分  类别为实物时展示-->
      <el-form-item v-if="ruleForm.goodsType === 'COUPONS'">
        <span
          class="coupons-box"
          v-for="(item, index) of lotteryActivityConfig.awards"
          :key="index"
        >
          <el-button
            type="primary"
            @click="addCoupons(index, '', 'draw')"
            v-if="!lotteryActivityConfig.awards[index].prize.prizeName"
            >添加优惠券</el-button
          >
          <el-button
            type="primary"
            v-if="lotteryActivityConfig.awards[index].prize.prizeName != ''"
            >{{
              lotteryActivityConfig.awards[index].prize.prizeName
            }}</el-button
          >
          <el-button
            type="primary"
            @click="addCoupons(index, '', 'draw')"
            v-if="lotteryActivityConfig.awards[index].prize.prizeName != ''"
            >重新选择优惠券</el-button
          >
        </span>
      </el-form-item>
      <el-form-item
        label="所需积分"
        prop="price"
        :rules="{
          required: true,
          message: '您没有填写所需积分',
          trigger: 'blur'
        }"
        v-if="ruleForm.goodsType === 'COUPONS'"
      >
        <el-input-number
          v-model="ruleForm.price"
          size="small"
          controls-position="right"
          :precision="0"
          :max="99999"
          :min="0"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="状态" prop="status1">
        <el-switch
          v-model="ruleForm.status1"
          :active-value="true"
          :inactive-value="false"
          active-color="#1DC8A4"
        ></el-switch>
      </el-form-item>
      <el-form-item label="每天可兑换次数" prop="changeNumber">
        <el-input-number
          v-model="ruleForm.changeNumber"
          size="small"
          controls-position="right"
          :precision="0"
          :max="99999"
          :min="0"
        ></el-input-number>
        次
      </el-form-item>
      <el-form-item label="序号" prop="sort">
        <el-input-number
          v-model="ruleForm.sort"
          size="small"
          controls-position="right"
          :precision="0"
          :max="99999"
          :min="1"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品详情" prop="remark">
        <div class="quill-box" style="width: 100%">
          <quill-editor
            ref="text"
            style="height: auto"
            v-model="ruleForm.remark"
            class="myQuillEditor"
            :options="editorOption"
            @change="onEditorChange($event)"
            @blur="onEditorBlur($event)"
          ></quill-editor>
        </div>

        <div class="limit">
          <!-- <span>{{ nowLength }}</span> / {{ maxLen }} -->
        </div>
      </el-form-item>
    </el-form>
    <!-- form-footer -->
    <div slot="footer" class="form-footer" style="">
      <el-button type="success" @click="onSubmit">保存</el-button>
      <el-button size="medium" @click="onCancel">取消</el-button>
    </div>
    <dialogUploadImg
      :dialogData="dialogUpData"
      @setImgInfo="setImgInfo"
      v-if="dialogUpData.isShow"
    ></dialogUploadImg>
    <addgoodsDialog
      :formInline="formInline"
      :total="total"
      :pages="pages"
      @backData="backData"
      @generlData="addCoupons()"
    ></addgoodsDialog>
  </div>
</template>

<script>
import dialogUploadImg from '@component/readManagement/readMine/dialogUploadImg' // 上传图片组件
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import addgoodsDialog from './addgoodsDialog' // 选择优惠券组件
import '@assets/css/quill.snow.css'
import { quillEditor } from 'vue-quill-editor'
import { clearTagMixins } from '@/mixins/clearTag'
import {
  addGoods,
  getGoodsDetail,
  editGoods
} from '@/api/flowerActive/goods/addEdit'
export default {
  mixins: [clearTagMixins],
  components: {
    uploadSingImg,
    dialogUploadImg,
    addgoodsDialog,
    quillEditor
  },
  data() {
    return {
      isAdd: true, //是否新增
      isCheck: false, //是否查看
      // 表单参数
      ruleForm: {
        id: '', //商品id
        name: '', // 商品名称
        image: '', // 商品图片
        stock: 0, //库存数量
        goodsType: '', //类别
        priceType:'',//货币类型
        priceShow: 0, //商品价格
        price: 0, //兑换所需鲜花 || 所需积分 因为选择优惠券和实物是互斥的，所以用同一个字段
        status1: false, //状态
        sort: 0, //序号
        changeNumber: 0, //兑换次数
        remark: '',
        couponsId: '' //所选优惠券的id
      },
      // 商品类型
      goodsTypeList: [
        { dictLabel: '实物', dictValue: 'PHYSICAL' },
        { dictLabel: '优惠券', dictValue: 'COUPONS' }
      ],
      total: 0,
      formInline: {
        show: false,
        // counpList: [],
        index: '',
        type: '',
        ind: ''
      },
      pages: {
        page: 1,
        size: 10
      },
      //  抽奖活动
      lotteryActivityConfig: {
        awards: [
          {
            prize: {
              couponId: '',
              maxPrizeNum: '',
              num: '',
              prizeName: '',
              type: 'VIRTUAL_PRIZE',
              virtualPrizeTypes: 'INTEGRAL'
            },
            probabilityOfWinning: ''
          }
        ],
        freeDraws: [],
        initialDraws: 0,
        payDraws: {
          maxNum: 0,
          num: 0,
          payType: 'INTEGRAL',
          open: false
        },
        remark: ''
      },
      // 富文本参数
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ header: 1 }, { header: 2 }],
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ['image']
            ],
            handlers: {
              image: (value) => {
                if (value) {
                  // 在这里编写图片按钮点击操作
                  let quill = this.$refs.text.quill
                  this.editorIndex = quill.getSelection()
                    ? quill.getSelection().index
                    : 0
                  this.dialogUpData.isShow = true
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          },
          clipboard: {
            matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]
          }
        },
        placeholder: '请输入正文'
      },
      dialogUpData: {
        isShow: false
      },
      // 富文本编辑

      textContent: '',
      nowLength: 0,
      maxLen: 500,
      overText: false, //富文本字数是否超过500
      // 表单校验
      rules: {
        name: {
          required: true,
          message: '您没有填写商品名称',
          trigger: 'blur'
        },
        image: [
          { required: true, message: '您没有上传商品图片', trigger: 'blur' }
        ],
        goodsType: {
          required: true,
          message: '您没有选择类别',
          trigger: ['blur', 'change']
        },
        stockNum: {
          required: true,
          message: '您没有填写库存数量',
          trigger: 'blur'
        },
        // price: {
        //   required: true,
        //   message: '您没有填写兑换所需鲜花数量或所需积分',
        //   trigger: 'blur',
        // },
        integralsNum: {
          required: true,
          message: '您没有填写所需积分数量',
          trigger: 'blur'
        }
      }
    }
  },
  created() {
    switch (this.$route.query.type) {
      case 'add':
        break
      case 'edit':
        this.isCheck = true
        this.getGoodsDetail(this.$route.query.id)
        this.$set(this.ruleForm, 'id', this.$route.query.id)
        break
      default:
        break
    }
    this.$set(this.ruleForm, 'goodsType', 'PHYSICAL')
  },
  methods: {
    // 编辑商品
    getGoodsDetail(id) {
      getGoodsDetail(id, (res) => {
        if (res) {
          this.ruleForm = res
          // 优惠券的回显
          if (this.ruleForm.couponsId) {
            this.lotteryActivityConfig.awards.forEach((item) => {
              item.prize.prizeName = this.ruleForm.couponName
            })
          }
          if (this.ruleForm.status === 'ON') {
            this.$set(this.ruleForm, 'status1', true)
          } else {
            this.$set(this.ruleForm, 'status1', false)
          }
        }
      })
    },
    // 商品图片
    getImgCover(url) {
      this.ruleForm.image = url
    },
    handleChange() {
      this.ruleForm.price = 0
    },
    //图片插入富文本编辑器
    setImgInfo(ary) {
      // 获取富文本组件实例
      let quill = this.$refs.text.quill
      if (ary) {
        // 插入图片，res为服务器返回的图片链接地址
        for (let item of ary) {
          quill.insertEmbed(this.editorIndex++, 'image', item.url)
        }
        // 调整光标到最后
        quill.setSelection(this.editorIndex)
      }
    },
    // 所选优惠券赋值到button上
    backData(backData, index, ind, type) {
      if (type == 'general') {
        this.inviteActivityConfig.inviteUserAwards.generalRewardAwards[
          index
        ].couponId = backData.id
        this.inviteActivityConfig.inviteUserAwards.generalRewardAwards[
          index
        ].prizeName = backData.couponName
      }
      if (type == 'beInvited') {
        this.inviteActivityConfig.inviteesUserAwards[index].couponId =
          backData.id
        this.inviteActivityConfig.inviteesUserAwards[index].prizeName =
          backData.couponName
      }
      if (type == 'stage') {
        this.inviteActivityConfig.inviteUserAwards.stageRewardConfig.stageRewards[
          index
        ].prize.couponId = backData.id
        this.inviteActivityConfig.inviteUserAwards.stageRewardConfig.stageRewards[
          index
        ].prize.prizeName = backData.couponName
      }
      if (type == 'behavior') {
        this.inviteActivityConfig.inviteUserAwards.behaviorRewards[
          index
        ].prize.couponId = backData.id
        this.inviteActivityConfig.inviteUserAwards.behaviorRewards[
          index
        ].prize.prizeName = backData.couponName
      }
      if (type == 'ladder') {
        this.inviteActivityConfig.inviteUserAwards.stage[index][ind].couponId =
          backData.id
        this.inviteActivityConfig.inviteUserAwards.stage[index][ind].prizeName =
          backData.couponName
      }
      if (type == 'draw') {
        this.lotteryActivityConfig.awards[index].prize.couponId = backData.id
        this.lotteryActivityConfig.awards[index].prize.prizeName =
          backData.couponName
        this.$set(this.ruleForm, 'couponsId', backData.id)
      }
    },
    // 添加优惠券
    addCoupons(index, ind, type) {
      this.formInline.index = index
      this.formInline.type = type
      this.formInline.ind = ind
      this.formInline.show = true
    },
    handleCustomMatcher(node, Delta) {
      if (this.clearStyle) {
        let ops = []
        Delta.ops.forEach((op) => {
          if (op.insert && typeof op.insert === 'string') {
            ops.push({
              insert: op.insert
            })
          }
        })
        Delta.ops = ops
        return Delta
      } else {
        return Delta
      }
    },
    // 富文本Change功能
    onEditorChange(event) {
      // let value = event.quill.getText()
      // this.textContent = value.slice(0, -1)
      // if (this.ruleForm.remark === '') {
      //   this.nowLength = 0
      // } else {
      //   this.nowLength = value.length - 1
      // }
      // this.overText = this.nowLength > this.maxLen ? true : false
      // if (this.overText) {
      //   this.$message.warning(`文章内容不超过${this.maxLen}字`)
      // }
    },
    // 富文本Blur功能
    onEditorBlur(event) {},
    // 提交功能
    onSubmit() {
      let addActivesss
      this.$refs['ruleForm'].validate((valid) => {
        addActivesss = valid
        if (!valid) {
          this.$message.warning('请检查必填项')
        } else {
          if (this.ruleForm.status1 == true) {
            this.ruleForm.status = 'ON'
          }
          if (this.ruleForm.status1 == false) {
            this.ruleForm.status = 'OFF'
          }
          //如果是实物货币类型就是鲜花类型
          if (this.ruleForm.goodsType === 'PHYSICAL') {
            this.ruleForm.priceType='FLOWERS'
          }
          //如果是优惠券货币类型就是积分
          if (this.ruleForm.goodsType === 'COUPONS') {
            this.ruleForm.priceType='INTEGRAL'
          }

          delete this.ruleForm.status1
          let params = {
            id: this.ruleForm.id, //商品id
            name: this.ruleForm.name, // 商品名称
            image: this.ruleForm.image, // 商品图片
            stock: this.ruleForm.stock, //库存数量
            goodsType: this.ruleForm.goodsType, //类别
            priceType:this.ruleForm.priceType,//货币类型
            priceShow: this.ruleForm.priceShow, //商品价格
            price: this.ruleForm.price, //兑换所需鲜花 || 所需积分
            status: this.ruleForm.status, //状态
            sort: this.ruleForm.sort, //序号
            remark: this.ruleForm.remark, //详情
            changeNumber: this.ruleForm.changeNumber, //兑换次数
            couponsId: this.ruleForm.couponsId //所选优惠券的id
          }
          if (this.ruleForm.id === '') {
            // 新增
            addGoods(this.ruleForm, (res) => {
              this.clearTag()
              this.$router.push({
                path: '/flowerActive/goodsList/index'
              })
            })
          } else {
            editGoods(this.ruleForm.id, params, (res) => {
              this.clearTag()
              this.$router.push({
                path: '/flowerActive/goodsList/index'
              })
            })
          }
        }
      })
    },
    onCancel() {
      this.clearTag()
    }
  }
}
</script>

<style lang="less" scoped>
.form-box {
  margin: 20px 20px;
  padding: 20px 20px;
}
.quill-box {
  margin-bottom: 30px;
}

.quill-editor {
  .ql-container {
    height: calc(100vh - 162px);
    .ql-editor {
      height: calc(~'100% - 30px');
    }
  }
}
.limit {
  height: 30px;
  line-height: 30px;
  text-align: right;
  margin: 20px 0 10px;
  padding-right: 10px;
  span {
    color: #f00;
  }
}

// 保存取消的样式
.form-footer {
  width: 200px;
  margin: 0 auto;
  margin-top: 76px;
  margin-bottom: 20px;
}
</style>
